package com.zbkj.crmeb.handler.orderconfirm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.zbkj.crmeb.enums.OrderStatusEnum;
import com.zbkj.crmeb.plat.by.dto.ByCommonConstant;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.service.StoreOrderInfoService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.task.plat.bieyang.dto.BieYangOrderConfirmDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author: wsl
 * @date: 2024/2/22 0022 22:28
 * @ClassName: ByOrderConfirmHandler
 */
@Component("byOrderConfirmHandler")
public class ByOrderConfirmHandler extends AbstractOrderConfirmHandler{
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;

    @Value("${by.plat.url}")
    private String platUrl;

    @Value("${by.plat.key}")
    private String platKey;
    private static final Logger logger = LoggerFactory.getLogger(ByOrderConfirmHandler.class);

    @Override
    public boolean doPreCheck(OrderConfirmContext context) {
        boolean flag = super.doPreCheck(context);
        if (!flag){
            return false;
        }
        StoreOrderInfo storeOrderInfo = context.getStoreOrderInfo();
        return storeOrderInfo.getChildOrderNumber().contains("BY");
    }

    @Override
    public boolean doHandler(OrderConfirmContext context) {
        logger.info("别样订单确认");
        StoreOrderInfo storeOrderInfo = context.getStoreOrderInfo();
        Integer id = storeOrderInfo.getOrderId();
        StoreOrder storeOrder = storeOrderService.getOne(Wrappers.<StoreOrder>lambdaQuery().eq(StoreOrder::getId, id));
        String orderId = storeOrder.getOrderId();
        String outOrderId = storeOrder.getOutOrderId();
        List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.list(Wrappers.<StoreOrderInfo>lambdaQuery().eq(StoreOrderInfo::getOrderId, id));
        // 校验子订单是否都是确认状态
        if (!validateChildrenOrderConfirm(storeOrderInfos)){
            return false;
        }
        // 向别样平台确认订单

        MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
        header.put("Authorization",Collections.singletonList(platKey));

        BieYangOrderConfirmDto bieYangOrderConfirmDto = new BieYangOrderConfirmDto();
        bieYangOrderConfirmDto.setMerchantOrderId(orderId);
        bieYangOrderConfirmDto.setOrderId(outOrderId);
        if (Objects.equals(storeOrder.getFeature(ByCommonConstant.IS_SPLIT),ByCommonConstant.IS_Y)){
            bieYangOrderConfirmDto.setOrderId(storeOrder.getFeature(ByCommonConstant.MAIN_ORDER_ID));
        }
        Map<String, List<BieYangOrderConfirmDto>> params = new HashMap<>();
        params.put("confirmList",Collections.singletonList(bieYangOrderConfirmDto));

        String paramsStr = JSON.toJSONString(params);
        logger.info("别样订单确认入参: {}",paramsStr);
        String result = post(platUrl+"/order/api/v1/orders/batch/confirm", paramsStr, header);
        logger.info("别样订单确认结果:{}",result);
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.get("error")!=null){
            JSONObject error = jsonObject.getJSONObject("error");
            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"别样订单确认失败:"+error.getString("message"));
            return false;
        }
        DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"别样订单确认结果:"+result);
        return true;
    }


    private boolean validateChildrenOrderConfirm(List<StoreOrderInfo> storeOrderInfos) {
        if (CollectionUtils.isEmpty(storeOrderInfos)){
            return false;
        }
        for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
            if (Objects.equals(storeOrderInfo.getStatus(), OrderStatusEnum.CONFIRM.getCode())){
                logger.error("子订单未全部确认有货,orderId: {}",storeOrderInfo.getOrderId());
                return false;
            }
        }
        return true;
    }

    public static String post(String url, String params, MultiValueMap<String, String> headers) {
        return request(url, params, headers, HttpMethod.POST, MediaType.APPLICATION_JSON);
    }

    /**
     * http请求
     *
     * @param url
     * @param params    请求参数
     * @param headers   请求头
     * @param method    请求方式
     * @param mediaType 参数类型
     * @return
     */
    public static String request(String url, Object params, MultiValueMap<String, String> headers, HttpMethod method, MediaType mediaType) {
        if (url == null || url.trim().isEmpty()) {
            return null;
        }
        RestTemplate client = new RestTemplate();
        // header
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers != null) {
            httpHeaders.addAll(headers);
        }
        // 提交方式：表单、json
        httpHeaders.setContentType(mediaType);
        HttpEntity<Object> httpEntity = new HttpEntity(params, httpHeaders);
        ResponseEntity<String> response = client.exchange(url, method, httpEntity, String.class);
        return response.getBody();
    }
}
